<?php
namespace hamster\tools\com;

// 基于redis防刷类
class CacheBrush
{
	public static $brush_prefix = 'webpay_brush_num_';
	public static $black_prefix = 'webpay_black_num_';

	/**
	 * 数量防刷
	 * @param string $key 关键字
	 * @param int $num 限制数量
	 * @param int $time 限制时长
	 * @return int|bool|null 当前数量|超标状态|缓存设置失败
	 */
	public static function brush_num($key, $num=1000, $time=60)
	{
		$cache_key = self::$brush_prefix . $key;
		$CacheAction = new CacheAction();

		$cache_data = $CacheAction->get($cache_key);
		if (!$cache_data) {
			// 新建缓存
			$cache_data['num'] = 1;
			$cache_data['time'] = time()+$time;
			$rel = $CacheAction->set($cache_key, json_encode($cache_data));
			if ($rel == 1) {
				$CacheAction->expire($cache_key, $time+60); // 缓存时间比默认的长60秒
				return $cache_data['num'];
			} else {
				return null; // （缓存设置失败）
			}
		} else {
			$cache_data = json_decode($cache_data, true);
			if ($cache_data['time'] < time()) { // 【数量不超标，时间已过】
				// 新建缓存
				$cache_data['num'] = 1;
				$cache_data['time'] = time()+$time;
				$CacheAction->set($cache_key, json_encode($cache_data));
				$CacheAction->expire($cache_key, $time+60);
			} elseif ($cache_data['num'] >= $num) { // 【数量超标】
				return false;
			} else { // 【数量未超，时间未超】
				$cache_data['num']++;
				$CacheAction->set($cache_key, json_encode($cache_data));
				$CacheAction->expire($cache_key, $time+60);
			}
			return $cache_data['num'];
		}
	}

	/**
	 * 清空缓存数
	 * @param string $key 关键字
	 */
	public static function clean_num($key)
	{
		$cache_key = self::$brush_prefix . $key;
		$CacheAction = new CacheAction();

		$CacheAction->del($cache_key);
	}

	/**
	 * 拉黑记录
	 * @param string $key 关键字
	 * @param int $num 限制数量
	 * @param int $brush_time 防刷时长
	 * @param int $black_time 拉黑时长
	 * @return bool|int|string
	 */
	public static function brush_black($key, $num, $brush_time, $black_time)
	{
		$brush_num = self::brush_num($key, $num, $brush_time);
		if ($brush_num === false || $brush_num === $num) { // 达到防刷上限
			$cache_key = self::$black_prefix . $key;
			$CacheAction = new CacheAction();

			$cache_data['time'] = time()+$black_time;
			$CacheAction->set($cache_key, json_encode($cache_data));
			$CacheAction->expire($cache_key, $black_time+60);

			return false; // 达到拉黑次数
		} elseif (is_numeric($brush_num)) {
			return ($num - $brush_num); // 剩余错误次数
		} else {
			return null; // 记录失败
		}
	}

	/**
	 * 判断是否拉黑
	 * @param string $key 关键字
	 * @return bool true-已经拉黑，false-没有拉黑
	 */
	public static function check_black($key)
	{
		$cache_key = self::$black_prefix . $key;
		$CacheAction = new CacheAction();

		$cache_data = $CacheAction->get($cache_key);
		if (!$cache_data) {
			return true;
		} else {
			$cache_data = json_decode($cache_data, true);
			if ($cache_data['time'] > time()) { // 【被拉黑时间内】
				return false;
			}
		}
		return true;
	}


}